import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Result } from './result.class';
import { RESPONSE_MESSAGE_KEY, RESPONSE_CODE_KEY } from './response.decorator';

/**
 * 响应拦截器
 * 基于 NestJS 拦截器实现
 * 与PHP/Java框架保持基本一致的响应格式，并添加timestamp字段
 * 
 * PHP格式: {data, msg, code}
 * Java格式: {code, msg, data}
 * NestJS格式: {code, msg, data, timestamp} (与Java基本一致，添加timestamp)
 */
@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, any> {
  constructor(private reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const responseMessage = this.reflector.getAllAndOverride<string>(
      RESPONSE_MESSAGE_KEY,
      [context.getHandler(), context.getClass()],
    );

    const responseCode = this.reflector.getAllAndOverride<string>(
      RESPONSE_CODE_KEY,
      [context.getHandler(), context.getClass()],
    );

    return next.handle().pipe(
      map((data) => {
        // 如果数据已经是 Result 格式，直接返回
        if (data && typeof data === 'object' && 'code' in data && 'msg' in data) {
          return data;
        }

        // 如果是分页数据
        if (
          data &&
          typeof data === 'object' &&
          'data' in data &&
          'meta' in data
        ) {
          return data;
        }

        // 普通数据包装 - 使用与PHP/Java一致的格式
        return Result.success(data, responseMessage || '操作成功');
      }),
    );
  }
}
